package com.harry.basis;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aopalliance.intercept.MethodInvocation;

import com.harry.utility.InnerUtils;

import lombok.Getter;

/**
 * 原本是为了简化 http 响应函数。
 * 将http请求过程中的关键数据打包并存在线程中，从而减少函数的传入参数使得函数声明看起来更简洁
 * 但是似乎此方式弊大于利，可能造成一与 http 响应无关的逻辑滥用此结构，故最后标记为 Deprecated
 */
@Deprecated
public abstract class ApiIntercepter {

	public abstract Object handle(MethodInvocation invocation) throws Throwable;

	public ApiIntercepter(String exp, int order) {
		this.exp = exp;
		this.order = order;
	}

	@Getter
	private int order;

	@Getter
	private String exp;

	@Getter
	private HttpServletRequest request;

	@Getter
	private HttpServletResponse response;

	@Getter
	private Map<String, Object> params;

	@Getter
	private Map<String, Object> dataout;

	@Getter
	private MethodInvocation invocation;

	@SuppressWarnings("unchecked")
	public final Object process(MethodInvocation invocation) throws Throwable {
		Object[] args = invocation.getArguments();
		this.invocation = invocation;
		this.request = InnerUtils.findArgs(args, HttpServletRequest.class);
		this.response = InnerUtils.findArgs(args, HttpServletResponse.class);
		this.params = InnerUtils.findArgs(args, Map.class);
		this.dataout = Map.class.isInstance(args[args.length - 1]) ? Map.class.cast(args[args.length - 1]) : null;
		return this.handle(invocation);
	}
}
